package com.acme.service.email;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;
import com.acme.domain.email.impl.QueueImpl;

public class EmailService implements Runnable {
	private Queue queue = new QueueImpl();
	
	public EmailService() {
		(new Thread(this)).start();
	}
	
	private static EmailService instance = new EmailService();
	public static EmailService getEmailService() {
		return instance;
	}

	@Override
	public void run() {
		while(queue.isOpened()) {
			Email email = this.queue.getEmail();
			if(email != null) {
				System.out.println(String.format("sending message #%s from %s to %s. subject: %s",
						email.getId(), email.getFrom(), email.getTo(), email.getSubject()));
			}
		}
	}
	
	public void sendNotificationEmail(Email email) {
		this.queue.addEmail(email);
	}

	public synchronized void close() {
		this.queue.close();
	}
}
